package com.syx.friend.Service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.syx.commoncore.Constant.CacheConstant;
import com.syx.commoncore.Model.Result;
import com.syx.commoncore.Model.TableDataInfoResult;
import com.syx.friend.ElasticSearch.QuestionRepository;
import com.syx.friend.Manager.QuestionCacheManager;
import com.syx.friend.Mapper.QuestionMapper;
import com.syx.friend.Model.question.DTO.QuestionQueryDTO;
import com.syx.friend.Model.question.Question;
import com.syx.friend.Model.question.VO.QuestionDetailVO;
import com.syx.friend.Model.question.VO.QuestionVO;
import com.syx.friend.Model.question.es.QuestionES;
import com.syx.friend.Service.IQuestionService;
import jakarta.annotation.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class IQuestionServiceImpl implements IQuestionService {

    @Resource
    QuestionRepository questionRepository;

    @Resource
    QuestionMapper questionMapper;
    @Resource
    QuestionCacheManager questionCacheManager;

    @Override
    public TableDataInfoResult list(QuestionQueryDTO questionQueryDTO) {
        long count = questionRepository.count();
        if (count<=0){
            //将数据库中的数据同步到es中
            refreshQuestion();
        }
        Page<QuestionES> questionESPage ;
        Sort sort=Sort.by(Sort.Direction.DESC,"createTime");
        Pageable pageable= PageRequest.of(questionQueryDTO.getPageNum()-1,questionQueryDTO.getPageSize(),sort);

        Integer difficulty = questionQueryDTO.getDifficulty();
        String keyword = questionQueryDTO.getKeyWord();
        if (difficulty == null && StrUtil.isEmpty(keyword)) {
            questionESPage = questionRepository.findAll(pageable);
        } else if (StrUtil.isEmpty(keyword)) {
            questionESPage = questionRepository.findQuestionByDifficulty(difficulty, pageable);
        } else if (difficulty == null) {
            questionESPage = questionRepository.findByTitleOrContent(keyword, keyword, pageable);
        } else {
            questionESPage = questionRepository.findByTitleOrContentAndDifficulty(keyword, keyword, difficulty, pageable);
        }
        long totalElements = questionESPage.getTotalElements();
        if (totalElements<=0){
            return TableDataInfoResult.empty();
        }
        List<QuestionES> content = questionESPage.getContent();
        List<QuestionVO> questionVOS = BeanUtil.copyToList(content, QuestionVO.class);

        return TableDataInfoResult.success(questionVOS,totalElements);




    }

    @Override
    public Result<QuestionDetailVO> detail(Long questionId) {
        //从es中查找，没找到就从数据库中查，并且同步到redis中
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        QuestionDetailVO questionDetailVO=new QuestionDetailVO();
        if (questionES!=null){
            //从es查到数据直接返回
            BeanUtil.copyProperties(questionES,questionDetailVO);
            return Result.success(questionDetailVO);
        }
        Question question = questionMapper.selectById(questionId);
        if (question==null){
            //数据库中也查不到
            return null;
        }
        refreshQuestion();
        BeanUtil.copyProperties(question,questionDetailVO);
        return Result.success(questionDetailVO);
    }

    @Override
    public Result<String> preQuestion(Long questionId) {
        //题目个数
        Long listSize = questionCacheManager.getListSize();
        if (listSize==null||listSize<=0 ){
            //刷新缓存，啥都没有的情况
            questionCacheManager.refreshCache();

        }
        //我认为用定时器刷新列表
        //从缓存中get数据
        //获取当前数据的前一个
        String preQuestionId=questionCacheManager.preQuestion(questionId).toString();
        return Result.success(preQuestionId);

    }

    @Override
    public Result<String> nextQuestion(Long questionId) {
        //题目个数
        Long listSize = questionCacheManager.getListSize();
        if (listSize==null||listSize<=0 ){
            //刷新缓存，啥都没有的情况
            questionCacheManager.refreshCache();

        }
        //我认为用定时器刷新列表
        //从缓存中get数据
        //获取当前数据的前一个
        String preQuestionId=questionCacheManager.nextQuestion(questionId).toString();
        return Result.success(preQuestionId);
    }

    @Override
    public Result<List<QuestionVO>> hotList() {
        Long hotListSize = questionCacheManager.getHostListSize();
        if (hotListSize <= 0) {
            //从数据库中刷数据
            List<Question> hotQuestionList = questionMapper.selectHotList();
            System.out.println(hotQuestionList);
            List<QuestionVO> questionVOS = BeanUtil.copyToList(hotQuestionList, QuestionVO.class);
            questionCacheManager.refreshHotListCache(questionVOS);


        }
        List<QuestionVO> questions = questionCacheManager.getQuestions(CacheConstant.QUESTION_HOST_LIST);
        System.out.println(questions);
        return Result.success(questions);
    }
    private void refreshQuestion() {
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<>());
        //去数据库中查找，如果没查到不要刷新es
        if (CollectionUtil.isEmpty(questionList)){
            return;
        }
        List<QuestionES> questionES = BeanUtil.copyToList(questionList, QuestionES.class);
        //
        questionRepository.saveAll(questionES);


    }
}
